<template>
  <!-- 自定义树组件，继承el-tree属性和方法 -->
  <div>
    <upper-template
      noSearchButton
      :noIcon="!vpHeader.search"
      :configIcon="false"
      style="height:42px;"
      search-place="left"
      v-if="vpHeader.show"
    >
      <div slot="buttonArea" class="top-title" v-if="vpHeader.text">
        <span class="vertical-bar"></span>
        {{ vpHeader.text }}
      </div>
      <div slot="searchArea" v-if="vpHeader.search">
        <onlyOneSearch
          v-model="filterText"
          placeholder="请输入名称"
          :search-method="filterTree"
        ></onlyOneSearch>
      </div>
    </upper-template>
    <div class="vp-tree-title" v-if="vpTitle">
      <span class="title_text">{{ vpTitle }}</span>
      <!-- <i class="el-icon-folder-opened" title="切换节点高度" @click="cutNodeHeight"></i> -->
    </div>
    <div
      class="body"
      v-loading="treeLoading"
      :element-loading-text="loadingText"
    >
      <div class="tree_box" :style="treeMaxHeight!=''?{maxHeight:treeMaxHeight}:{}">
        <el-tree
          v-bind="{ ...$props, ...$attrs }"
          v-on="$listeners"
          :filter-node-method="filterNode"
          ref="vptree"
          icon-class="iconfont icon-treenodeS"
        >
          <slot></slot>
        </el-tree>
      </div>
      <div v-if="footerBtn && hasData">
        <el-tag @click.native="setAllExpand(true)" class="footerBtn" :title="'当前默认展开外'+expanMaxLevel+'层'"
          >展开</el-tag
        >
        <el-tag @click.native="setAllExpand(false)" class="footerBtn" :title="'当前默认收起外'+expanMaxLevel+'层'"
          >收起</el-tag
        >
      </div>
    </div>
  </div>
</template>

<script>
export default {
  // header标题，为空则头部不显示
  props: {
    vpHeader: {
      type: Object,
      default: () => {
        return {
          show: false, // 是否显示头部
          text: "", // 头部文字
          search: true, // 是否开启节点过滤
          name: "label" //过滤字段
        };
      }
    },
    vpTitle: {
      type: String,
      default: ""
    },
    footerBtn: {
      type: Boolean,
      default: true
    },
    // 点击展开或收缩按钮最大生效的层级，避免层级过多的展开操作使页面卡顿
    expanMaxLevel:{
      type:Number,
      default: 3
    },
    // 树最大高
    treeMaxHeight:{
      type:String,
      default: "573px"
    },
  },
  created() {},
  computed: {
    hasData() {
      let data = this.$attrs.data,
        flg = false;
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].children && data[i].children.length > 0) {
            flg = true;
            break;
          }
        }
      }
      return flg;
    },
  },
  mounted() {
    this.$tree = this.$refs.vptree;
    // this.$nextTick(() => {
    //   setTimeout(() => {
    //     console.log( this.$tree,' this.$tree')
    //     this.state ? this.nowStatusC() : this.nowStatus();
    //   }, 100);
    // });
    this.elTreeMethodsExtend();
  },
  watch: {
    filterText(newV, oldV) {
      if (newV == "") {
        this.filterTree();
      }
    }
  },
  data() {
    return {
      inheritAttrs: false,
      state: false,
      filterText: "",
      nodeHeight: "40px",
      treeLoading: false,
      loadingText: ""
    };
  },

  methods: {
    // 继承el-tree其他方法,使用时查看elementui文档即可
    elTreeMethodsExtend() {
      // 这里可以为el-tree的方法改名字
      let fns = {
        filter: "filter",
        updateKeyChildren: "updateKeyChildren",
        getCheckedNodes: "getCheckedNodes",
        setCheckedNodes: "setCheckedNodes",
        getCheckedKeys: "getCheckedKeys",
        setCheckedKeys: "setCheckedKeys",
        setChecked: "setChecked",
        getHalfCheckedNodes: "getHalfCheckedNodes",
        getHalfCheckedKeys: "getHalfCheckedKeys",
        getCurrentKey: "getCurrentKey",
        getCurrentNode: "getCurrentNode",
        setCurrentKey: "setCurrentKey",
        setCurrentNode: "setCurrentNode",
        getNode: "getNode",
        remove: "remove",
        append: "append	",
        insertBefore: "insertBefore",
        insertAfter: "insertAfter"
      };
      for (const key in fns) {
        this[fns[key]] = this.$refs.vptree[key];
      }
    },
    filterTree() {
      this.loadingText = "正在检索";
      this.treeLoading = true;
      setTimeout(() => {
        this.filter(this.filterText);
        this.treeLoading = false;
      }, 500);
    },
    filterNode(value, data) {
      console.log(this.$props);
      if (!value) return true;
      return data[this.vpHeader.name].indexOf(value) !== -1;
    },
    // 辨认现在是展开还是收缩状态
    nowStatus(a, b, c) {
      if (b && b.level != 1) return;
      let flag = true;
      var nodes = this.$refs.vptree.store.nodesMap;
      var list = [];
      console.log(nodes);
      for (const key in nodes) {
        if (nodes[key].level === 1) {
          list.push(nodes[key]);
        }
      }
      for (let j = 0; j < list.length; j++) {
        if (list[j].expanded) {
          flag = false;
        }
      }
      this.state = flag;
      // console.log(flag?'展开':'收缩')
    },
    nowStatusC(a, b, c) {
      if (b && b.level != 1) return;
      let flag = true;
      var nodes = this.$refs.vptree.store.nodesMap;
      var list = [];
      console.log(nodes);
      for (const key in nodes) {
        if (nodes[key].level === 1) {
          list.push(nodes[key]);
        }
      }
      for (let j = 0; j < list.length; j++) {
        if (list[j].expanded) {
          flag = false;
        }
      }
      this.state = !flag;
    },
    //设置全部展开和折叠。state参数为bool值
    setAllExpand(state) {
      if (this.treeLoading) return;
      let nodes = this.$refs.vptree.store._getAllNodes();
        let total = nodes.length;
        this.loadingText = `当前数据量为${total}条，正在处理...`;
        this.treeLoading = true;
        setTimeout(() => {
          // console.log(nodes)
          for (let i = 0; i < nodes.length; i++) {
            // 由于性能原因，默认只对三层以内的数据进行展开或收缩
            if(nodes[i].level<=this.expanMaxLevel){nodes[i].expanded = state;}
          }
          this.$nextTick(() => {
            this.treeLoading = false;
          });
        }, 500);
      // this.state = !state;
    },
    // 切换节点高度
    cutNodeHeight() {
      if (this.nodeHeight == "40px") {
        this.nodeHeight = "10px";
      } else {
        this.nodeHeight = "40px";
      }
    }
  }
};
</script>

<style lang="scss" vars= {nodeHeight} scoped>
.vp-tree-title {
  height: 40px;
  background: #ecf1fc;
  border-radius: 2px 2px 0px 0px;
  position: relative;
  .title_text {
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #6f76a5;
    line-height: 40px;
    position: absolute;
    top: 50%;
    left: 20px;
    transform: translateY(-50%);
  }
  .el-icon-folder-opened {
    color: #6f76a5;
    float: right;
    line-height: 40px;
    margin-right: 10px;
    cursor: pointer;
  }
}
.tree_box {
  border-radius: 0px 0px 2px 2px;
  border: 1px solid #eaebed;
  max-height: 573px;
  overflow-y: auto;
}
/deep/.el-tree-node {
  background: #fff;
}
/deep/.el-tree-node__content {
  height: 40px;
  border-bottom: 1px solid #eaebed;
  font-size: 12px;
  border-left: 15px solid transparent;
}
.el-tag {
  margin: 9px 3px;
  width: 65px;
  height: 26px;
  border: 1px solid #dce0e6;
  background-color: #fff;
  line-height: 26px;
  text-align: center;
  cursor: pointer;
  color: #999;
}
.top-title {
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #000000;
  line-height: 20px;
  vertical-align: middle;
  margin-top: 9px;
}
.vertical-bar {
  line-height: 20px;
  font-weight: 500px;
}

// tree组件的icon修改，需要设置icon-class
/deep/.el-tree-node__content > .el-tree-node__expand-icon {
  padding: 0px;
  font-size: 12px;
}
/deep/.el-tree-node__expand-icon::before {
  // content: "\e7a0";
  color: #769aff;
}

/deep/.expanded.el-tree-node__expand-icon::before {
  content: "\e64a";
}

/deep/.is-leaf.el-tree-node__expand-icon::before {
  content: "\e647";
  color: #fec24e;
}
.footerBtn:hover {
  border: 1px solid #ccc;
  color: #6f76a5;
}
</style>